import 'babel-polyfill'
import promise from 'es6-promise';
// 兼容 Promise
promise.polyfill();

String.prototype.replaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
}



import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

import CryptoJS from 'crypto-js'
//加密 window.GWO().debug.$encrypt("2323"); window.GWO().debug.$decrypt("52ojs914smWyuDFRT1JrTA==");
Vue.prototype.$encrypt = function (word, keyStr) {
  keyStr = keyStr ? keyStr : 'abcdefgabcdefg12';
  var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  return encrypted.toString();
}
//解密
Vue.prototype.$decrypt = function (word, keyStr) {
  keyStr = keyStr ? keyStr : 'abcdefgabcdefg12';
  var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

// 扫码枪出发函数
Vue.prototype.onEnter = function(event,pm_fun){
  //vue中使用的地方: 具体的函数 do_inputspbar 中有window.alert的时候,可能导致event.target._value 和 event.keyCode 123F12 的顺序先后错乱
  //<span><input v-model="inputspbar" ref="defFocused" @keyup="onEnter($event,do_inputspbar)" style="width:120px;"></input></span>
  //<span><van-button :loading ="loading" loading-text="输入" @click="do_inputspbar(inputspbar)">输入</van-button> </span>
  //ref="defFocused" 设置焦点 this.$nextTick(() => { this.$refs["defFocused"].focus(); }); //mounted()中设置默认活动焦点的编辑框
  //alert(JSON.stringify(event)+' '+event.keyCode +"|"+event.key )
  if(typeof(event) != 'undefined' && typeof(event.target) != 'undefined' && typeof(event.target._value) != 'undefined'){
    if(event.target._value > ''){}else{ return } //没有数据不触发
  }
  if (event.keyCode === 10 || event.keyCode === 13 || event.keyCode === 0 || event.keyCode === 255 || (event.keyCode >= 112 && event.keyCode <= 135) ) { //enter 或 f1-f24
    event.target.selectionStart = 0; event.target.selectionEnd = event.target._value.length; //全选
    pm_fun(event.target._value); //兼容处理回车键 和 扫描枪的带的功能键
  }
}


// import moment from 'moment' // 时间格式化插件
// Vue.prototype.$moment = moment

// import myPopup from './assets/js/popup.js'
// Vue.prototype.$myPopup = myPopup.install
// import myComPopup from './assets/js/confrim_pop.js'
// Vue.prototype.$myComPopup = myComPopup.install
// import myPrompt from './assets/js/prompt_prop.js'
// Vue.prototype.$myPrompt = myPrompt.install
//带返回的
// _self.$myPopup({
//   title: '我是标题',
//   content: '我是内容',
//   btnText: '我是按钮',
// thenclick:() => {

// },
// })
// 带确认返回的
// _self.$myComPopup({
// title: '我是标题',
// content: '我是内容',
// btnText: '我是按钮',
// thenClick:() => {},
// catchClick:()=>{},
// })
// 带输入的
// this.$myPrompt({
// 	   title: '我是标题',
// 	   content: '我是内容',
// 	   btnText1: '确认',
// 	   btnText2: '返回',
// 	   thenClick:(value) => {

// 	   },
// 	   catchClick:()=>{

// 	   },
// })

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
//import store from './store/index'
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)
import Vuex from 'vuex'//引入vuex
Vue.use(Vuex); //使用 vuex

// 引入动画库
import animated from 'animate.css'
Vue.use(animated)


import Axios from 'axios' //全局引入axios
Axios.defaults.withCredentials = true;//让ajax携带cookie
//也就是说Access-Control-Allow-Credentials设置为true的情况下
//Access-Control-Allow-Origin不能设置为*
import qs from 'qs'
Vue.prototype.qs = qs //加载

//import {ActionSheet} from 'vue-ydui/dist/lib.rem/actionsheet';
//import {SendCode} from 'vue-ydui/dist/lib.rem/sendcode';

/////////////// 自定义的全局可用的常量变量和函数声明 START
//每一个vue组件都是Vue的实例,所以组件内this可以拿到Vue.prototype上添加的属性和方法,
//系统实际只 new Vue({  el: '#app', 一个所以,也可用此代替 this.$store.state 进行的组件间的常量数据共享
Vue.prototype.$axios = Axios; //加载
//取用户的登陆信息 <script>  var _gwo_={};  function GWO(){ return _gwo_;} </script>
//window.GWO()是一个在index.html中定义的函数, 用 _gwo_ 记录变量,防Vue.prototype.xxx都是只读这种问题,也类似一个单例吧 //用这种方式挂载的变量, 一刷新就没有了, 不能用,注意
// 在login 中写入值 this.GWO().gUSER = this.arr2Obj(res.data.user)[0];
// 在其他的页面中读取值 如: alert("this.GWO().gUSER.ryname=>"+this.GWO().gUSER.ryname)
Vue.prototype.GWO = function (pm_notchklogin) {
  var t = window.GWO();
  if (t.gUSER == null || typeof (t.gUSER) == 'undefined') { //未挂载,或刷新造成的丢失用$store刷新一下
    try {
      var ls_jsonstr = localStorage.getItem('Authorization');
      if (ls_jsonstr > '') {
        t.gUSER = JSON.parse(ls_jsonstr); //用本地缓存的信息来初始化
      }
    } catch (error) {
      t.gUSER = { operatorid: null, opername: null, };
    }
  }
  try { if (t.gUSER.apptitle > '' && t.gUSER.apptitle != document.title) { document.title = t.gUSER.apptitle; } } catch (error1) { }
  if (pm_notchklogin) {
    if (t.gUSER && t.gUSER.operatorid && t.gUSER.operatorid > '') {
      //有这些信息,认为已经登陆成功了
    } else {
      t.gUSER = { };
    }
  } else { //是否检查必须是已登陆状态
    if (t.gUSER && t.gUSER.operatorid && t.gUSER.operatorid > '') {
      //有这些信息,认为已经登陆成功了
    } else {
			this.$alert('您还没登陆!', '提示', {confirmButtonText: '返回'});
      this.$router.push({ path: '/login' });
    }
  }
  return window.GWO();
}
Vue.prototype.URLBASE = window.GWO().URLBASE; //'http://192.168.1.28:8080/rfa/';
Vue.prototype.API = window.GWO().URLBASE + 'data.jsp'; //'http://192.168.1.10:18080/rfa/data.jsp' //服务端的地址, 定义到全局变量,其他的地方要访问,直接用 this.API即可
//
Vue.prototype.getLoginMagicStr = function () {
  var ls_kqid = localStorage.getItem('kqid'); //库区ID
  var ls_user = localStorage.getItem('user'); //读取本地存储的用户名和密码
  var ls_pswd = localStorage.getItem('pswd'); //注意localStorage(不区分path) 和 cookie(区分path)
  return this.$encrypt(ls_kqid + '#@#' + ls_user + '#@#' + ls_pswd); //这个header信息要是被人截获缓存了,就相关于用户名密码被人截获缓存了
  //带自定义的 header 会触发浏览器发preflight 请求
}

Vue.prototype.logout = function () { //注销,退出
  var _self = this;
  var rnd=Math.random(); rnd=Math.floor(rnd*10000);
  var ldemodata = [{retval:0, errmsg:'提交成功'},]
  // dologoutajax 是否需要调用这个
  _self.MYPOST({'method':'dologoutajax', 'rand':rnd },'退出登录',false, ldemodata, //注意是false, 不在post中弹出
  function(ret_obj, ret_iserr,ret_errmess,ret_oldresp){
    let instance = _self.$message.success('退出成功');
     _self.GWO(true).gUSER = null; //删除已登陆信息
    localStorage.removeItem('user'); localStorage.removeItem('pswd');localStorage.removeItem('Authorization');  //删除本地存储的用户名和密码
    var url = window.location.href.toString().replace(window.location.hash, ''); //纯url的部分
    setTimeout(() => {
      try{ instance.close(); }catch(ee){}
      window.location.href=url; //注销后重新加载
    }, 200);
  });
  //this.$router.push("/f0login"); //用 window.location.href 强制加载一下
},

// console.log("测试取单号可用 window.GWO().vue.SETBILLID(null,function(pm_billid){ console.log('取单号的返回为:'+pm_billid);});");
Vue.prototype.SETBILLID = function (pm_url, pm_fun) { //取单号
  if (this.API.indexOf("192.168.") > 0) { //wap端是单独的项目,ajax访问是跨域访问,正式的时候是相对路径,不是跨域
    //debugger;
    this.$axios.interceptors.request.use(function (config) {
      config.withCredentials = true
      return config
    });
  }
  var rnd = Math.random(); rnd = Math.floor(rnd * 10000); var THISTHIS = this;
  var ls_url = pm_url; if (ls_url == null) { ls_url = this.API; }
  var dl_MagicStr = this.getLoginMagicStr();
  var ls_pm = this.qs.stringify({ 'method': 'getbillid', 'rand': rnd, 'upautomagic': dl_MagicStr });
  this.$axios.post(ls_url, ls_pm).then(function (response) {
    if (response.status == 200) { //访问网络异常,如地址错误,断网等
      var rdata = response.data;
      if (typeof (rdata.billid) == 'string') {
        pm_fun(rdata.billid); /* rdata => {"retval":"0","billid":"20190304164230055020"} */
      } else {
				THISTHIS.$alert('取单号信息错!', '提示', {confirmButtonText: '返回'});
      }
    } else { //应该是只有status=200的,错误已经自动滤除了
			THISTHIS.$alert('取单号网络错误' + response.status, '提示', {confirmButtonText: '返回'});
      console.log(response);
    }
  }).catch(function (error) {
		THISTHIS.$alert('取单号信息错！' + error, '提示', {confirmButtonText: '返回'});
    console.log('取单号信息错:'); console.log(error)
  });
}


/**
 * 通用的取数据的API接口,传入参数为
 * pm_args 传入的访问参数json格式的 { 'method':'dgate','pname':'p_mgrfbxx001','i':[ 'opmode','qry', 'fy_pno','1', 'fy_psize','10',  'qyid','1', 'billid','%', 'xxtype','ZZJG'] } 一个传入的demo
 * pm_tipstr 网络错误时提示信息的前缀
 * pm_ynerrtip 出错时是否提示
 * pm_demojsonobj 测试用的demo json object,用于原型设计阶段,无真实api的时候 的demo数据
 * pm_cbfunc_obj_iserr_errmess_oldresp 争取返回的回调函数 new function(ret_obj, ret_iserr, ret_errmess, oldresp){ ... }
 *   ret_obj --  服务端返回的[{fname1:fieldv11,fname2:fieldv12,...},{fname1:fieldv21,fname2:fieldv22,...}]数据结果集
 *   ret_iserr -- bool型的服务端是否返回错误
 *   ret_errmess -- 服务端返回的错误信息
 *   oldresp 原始的http返回
 //2020-05-26 增加参数 ulstsecs=5缓存5秒钟,<=0的不缓存
 //2020-05-26 增加参数 MRS=Y,表示按多结果集的方式返回,减少和服务器的交互,提升效率
 */
//
Vue.prototype.OFFLINEDEVMODE = false;  //是否离线开发模式, 此模式下不联网,适用传入的demo数据进行处理
// console.log("测试MYPOST window.GWO().vue.MYPOST({ 'method':'dgate','pname':'p_mgrfbxx001','i':[ 'opmode','qry', 'fy_pno','1', 'fy_psize','10',  'qyid','1', 'billid','%', 'xxtype','ZZJG'] },'',true,{demo:'demo'},function(ret_obj, ret_iserr, ret_errmess, oldresp){ console.log('回调得到的返回值:');console.log(ret_obj);});");
Vue.prototype.MYPOST = function (pm_args, pm_tipstr, pm_ynerrtip, pm_demojsonobj, pm_cbfunc_obj_iserr_errmess_oldresp) {
  if (this.API.indexOf("192.168.") > 0) { //wap端是单独的项目,ajax访问是跨域访问,正式的时候是相对路径,不是跨域
    //debugger;
    this.$axios.interceptors.request.use(function (config) {
      config.withCredentials = true
      return config
    });
  }
	// this.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
  var pm_ostr = ''; var THISTHIS = this;
  //try {  pm_ostr = JSON.stringify(pm_args);  }catch(eeeee){ pm_ostr = ''; } //不提示,就不用处理
  var rnd = Math.random(); rnd = Math.floor(rnd * 10000); var THATTHIS = this;
  // console.log('--------------------'+pm_tipstr+'-----------------------START');
  // console.log('pm_args=>'); console.log(pm_args);
  // console.log('pm_demojsonobj=>'); console.log(pm_demojsonobj);
  // console.log('--------------------'+pm_tipstr+'-----------------------END');
  //必须传入回调函数
  if (pm_cbfunc_obj_iserr_errmess_oldresp == null || typeof (pm_cbfunc_obj_iserr_errmess_oldresp) != 'function') {
    var tip = '取' + pm_tipstr + '信息offline_dev_mode错！传入的回调函数 pm_cbfunc_obj_iserr_errmess 不正确,';
		THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
    console.log(tip); console.log(pm_cbfunc_obj_iserr_errmess_oldresp);
  }
  if (pm_args == null) { pm_args = {}; }
  var dl_MagicStr = this.getLoginMagicStr(); if (dl_MagicStr > '') { pm_args.upautomagic = dl_MagicStr }
  try{ //2023-01-12 尝试将 原来的i数组, 用base64编码后发送到后台
    if(pm_args.method == 'dgate' && window.USEARGSISTR && typeof(pm_args.i) == 'object' && pm_args.i.length
      && window.btoa && unescape && encodeURIComponent && JSON &&JSON.stringify){
      pm_args.ienc64strxx = window.btoa(unescape(encodeURIComponent(JSON.stringify(pm_args.i)))); //java端的接收变为
      //window.btoa(unescape(encodeURIComponent(JSON.stringify(["1","2","3","4","5"]))))
      //译者注:在js引擎内部,encodeURIComponent(str)相当于escape(unicodeToUTF8(str))
      //所以可以推导出unicodeToUTF8(str)等同于unescape(encodeURIComponent(str))
      pm_args.i = []; //不传这个参数,可能明文的被防火墙 敏感字符给拦截了
    }
  }catch(encodebase64){}
  //
  if (this.OFFLINEDEVMODE) {
    pm_cbfunc_obj_iserr_errmess_oldresp(pm_demojsonobj, false, null, pm_demojsonobj); /* rdata => {"retval":"0","billid":"20190304164230055020"} */
  } else { //this.qs.stringify 将json参数用 a=a&b=b&i[]=1&i[]=2&i[]=3& 的形式的访问
    this.$axios.post(this.API, this.qs.stringify(pm_args)).then((response) => {
      //throw "经测试then中抛出的异常信息,能被this.qs.stringify(pm_args)).then(内部函数引发异常).catch(能捕获)";
      console.log('取'+pm_tipstr + "信息,传入=>"); console.log(pm_args); console.log("原始返回=>"); console.log(response);

      if (response.status == 200) { //访问网络异常,如地址错误,断网等
        var rdata = response.data;
        //错误时:"{\"errcode\":\"-1\",\"errmsg\":"+JSON.toJSONString(ret_mess)+"}";
        if (typeof (rdata.errcode) != "undefined" || typeof (rdata.errmsg) != "undefined") {
          // var tip = rdata.errmsg ; //'取'+pm_tipstr+'信息服务器返回错,' +rdata.errmsg ;
          var tip = rdata.errmsg;
          var li_errpos = tip.indexOf('ERR:');  if (li_errpos >= 0) { tip = tip.substr(li_errpos + 4); }else{ li_errpos = tip.indexOf('ERR'); if (li_errpos >= 0) { tip = tip.substr(li_errpos + 3); } }
          if (rdata.errmsg.indexOf('ERR请先登陆后') >= 0 || rdata.errmsg.indexOf('登陆已过期') >= 0 || rdata.errmsg.indexOf('qyid不一致') > 0 || rdata.errmsg.indexOf('QYID不一致') > 0) {
            //alert('访问数据时,提示未登录:'+pm_ostr+','+rdata.errmsg);
            localStorage.removeItem('Authorization');
            THATTHIS.$router.push({ path: '/login' }); //清空本地得登陆信息,然后跳到登陆页
            return;
          }
          if (pm_ynerrtip){
						THISTHIS.$store.commit('hideLoading');
						THISTHIS.$dialog.alert({title: '提示',message:tip,confirmButtonColor:'#f69'}) //每次后台报错就走这里了
          } else {pm_cbfunc_obj_iserr_errmess_oldresp(null, true, tip, response);}
        } else {
          var rtn_obj = null;
          if (typeof (pm_args.MRS) == 'string' && pm_args.MRS == 'Y') { //2020-05-26一个程序包调用,返回多个结果集的情况; 还有结果集标识,带入的查询条件
            for (var mrsi = 0; mrsi < rdata.data.length; mrsi++) {
              var t_obj = null; if (rtn_obj == null) { rtn_obj = []; }
              try { t_obj = THATTHIS.arr2Obj(rdata.data[mrsi]); } catch (eTrans) { }
              rtn_obj[rtn_obj.length] = t_obj; //和下面的聚合方式是不一样的
            }//多结果集模式,返回的将是一个数组
          } else {
            try { rtn_obj = THATTHIS.arr2Obj(rdata.data); } catch (eTrans) { }
          }
          pm_cbfunc_obj_iserr_errmess_oldresp(rtn_obj, false, null, response);
        }
      } else { //应该是只有status=200的,错误已经自动滤除了
        var tip = '取' + pm_tipstr + '网络错误' + response.status;
        if (pm_ynerrtip) {
          var li_errpos = tip.indexOf('ERR:');  if (li_errpos >= 0) { tip = tip.substr(li_errpos + 4); }else{ li_errpos = tip.indexOf('ERR'); if (li_errpos >= 0) { tip = tip.substr(li_errpos + 3); } }
					THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#f00'})
          // THATTHIS.$myPopup({ title: '操作失败', content: tip, btnText: '返回', thenclick: () => { } })
          // THATTHIS.$messagebox.alert(tip);
        } else { pm_cbfunc_obj_iserr_errmess_oldresp(null, true, tip, response); }
      }
    }).catch(function (error) {
      var tip = '取' + pm_tipstr + '异常错,' + error;
      console.log(tip); console.log(error);
      if (pm_ynerrtip) {
        var li_errpos = tip.indexOf('ERR:');  if (li_errpos >= 0) { tip = tip.substr(li_errpos + 4); }else{ li_errpos = tip.indexOf('ERR'); if (li_errpos >= 0) { tip = tip.substr(li_errpos + 3); } }
        // THISTHIS.$alert(tip,'操作失败', {confirmButtonText: '返回'});
				THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
        // THATTHIS.$myPopup({ title: '操作失败', content: tip, btnText: '返回', thenclick: () => { } })
        // alert(tip);
        //THATTHIS.$messagebox.alert(tip);
      } else { pm_cbfunc_obj_iserr_errmess_oldresp(null, true, tip, error); }
    });
  }
}
/*传入的json的例子
var lobj_json = [{pname:"p_mgrfbxx001",i:["opmode","qry","qyid","1"]}]; //单数据集
    lobj_json = [{pname:"p_mgrfbxx001",i:["opmode","qry","qyid","1"]},
                  {pname:"p_mgrzdypage001",i:["opmode","qry","qyid","1"]} ]; //2个不相关数据集
    lobj_json = [{id:"xs1",pname:"p_mgrxsdd001",i:["opmode","qry","operatorid","1","opername","1"]},
                  {pname:"p_mgrxsdd001",i:["opmode","mqryxsdd002","qyid","1"],"rpid":"xs1","rrow":"A",rpv:[{pn:"bill",cn:"bill"}] }  ]; //父结果集 和 子结果集相关 的情况
//2020-05-26 增加参数 ulstsecs=5缓存5秒钟, 传了此参数>0就会缓存,有缓存取缓存
*/
Vue.prototype.MYPOSTPL = function (urlargs, pmarr_postjson, pm_tipstr, pm_ynerrtip, pm_demojsonobj, pm_cbfunc_obj_iserr_errmess_oldresp) { //批量提交一组查询,然后聚合为结果集数组进行返回
  if (this.API.indexOf("192.168.") > 0) { //wap端是单独的项目,ajax访问是跨域访问,正式的时候是相对路径,不是跨域
    //debugger;
    this.$axios.interceptors.request.use(function (config) {
      config.withCredentials = true
      return config
    });
  }

  var rnd = Math.random(); rnd = Math.floor(rnd * 10000); var THATTHIS = this;
  //必须传入回调函数
  if (pm_cbfunc_obj_iserr_errmess_oldresp == null || typeof (pm_cbfunc_obj_iserr_errmess_oldresp) != 'function') {
    var tip = '取' + pm_tipstr + '信息offline_dev_mode错！传入的回调函数 pm_cbfunc_obj_iserr_errmess 不正确,';
		THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
		// THISTHIS.$alert(tip,'操作失败', {confirmButtonText: '返回'});
    // THATTHIS.$myPopup({ title: '操作失败', content: tip, btnText: '返回', thenclick: () => { } })
    console.log(tip); console.log(pm_cbfunc_obj_iserr_errmess_oldresp);
  }
  if (urlargs == null) { urlargs = {}; }
  var dl_MagicStr = this.getLoginMagicStr(); if (dl_MagicStr > '') { urlargs.upautomagic = dl_MagicStr }
  if (typeof (urlargs.method) == 'string' && urlargs.method > '') { } else { urlargs.method = 'dgatemrsmp'; }
  if (typeof (urlargs.ulstsecs) != 'undefined' && parseInt(urlargs.ulstsecs) > 0) { urlargs.ulstsecs = parseInt(urlargs.ulstsecs); } else { urlargs.ulstsecs = -1; }
  if (this.OFFLINEDEVMODE) {
    pm_cbfunc_obj_iserr_errmess_oldresp(pm_demojsonobj, false, null, pm_demojsonobj); /* rdata => {"retval":"0","billid":"20190304164230055020"} */
  } else { //这种方式直接post的json的文本,有上下级关系,用wwwurlencode方式不好表示
    this.$axios({
      method: "post", url: this.API + "?method=" + urlargs.method + (urlargs.ulstsecs > 0 ? "&ulstsecs=" + urlargs.ulstsecs : ""),
      data: JSON.stringify(pmarr_postjson), headers: { 'Content-Type': 'text/plain;charset=UTF-8' }
    } //简单数据请求类型
    ).then((response) => {
      console.log('取' + pm_tipstr + "信息,传入=>"); console.log(pmarr_postjson); console.log("原始返回=>"); console.log(response);
      if (response.status == 200) { //访问网络异常,如地址错误,断网等
        var rdata = response.data;
        if (typeof (rdata.errcode) != "undefined" || typeof (rdata.errmsg) != "undefined") {
          var tip = rdata.errmsg;
          var li_errpos = tip.indexOf('ERR:');  if (li_errpos >= 0) { tip = tip.substr(li_errpos + 4); }else{ li_errpos = tip.indexOf('ERR'); if (li_errpos >= 0) { tip = tip.substr(li_errpos + 3); } }
          if (rdata.errmsg.indexOf('ERR请先登陆后') >= 0 || rdata.errmsg.indexOf('登陆已过期') >= 0 || rdata.errmsg.indexOf('qyid不一致') > 0 || rdata.errmsg.indexOf('QYID不一致') > 0) {
            localStorage.removeItem('Authorization'); THATTHIS.$router.push({ path: '/login' }); //清空本地得登陆信息,然后跳到登陆页
            return;
          }
          if (pm_ynerrtip) {
						THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
						// THISTHIS.$alert(tip,'操作失败', {confirmButtonText: '返回'});
            // THATTHIS.$myPopup({ title: '操作失败', content: tip, btnText: '返回', thenclick: () => { } })
          } else { pm_cbfunc_obj_iserr_errmess_oldresp(null, true, tip, response); }
        } else {
          var rtn_obj = null;
          //2020-05-26一组程序包查询聚合为一次返回多个结果集的数组; 返回的结果集无查询条件,结果集标识等
          for (var mrsi = 0; mrsi < rdata.data.length; mrsi++) {
            if (rtn_obj == null) { rtn_obj = []; }
            var t_obj = rdata.data[mrsi];  //和 一个查询,返回多个结果集是不一样的
            try { t_obj.data = THATTHIS.arr2Obj(t_obj.data); } catch (eTrans) { }
            rtn_obj[rtn_obj.length] = t_obj;
          }//多结果集模式,返回的将是一个数组
          pm_cbfunc_obj_iserr_errmess_oldresp(rtn_obj, false, null, response);
        }
      } else { //应该是只有status=200的,错误已经自动滤除了
        var tip = '取' + pm_tipstr + '网络错误' + response.status;
        if (pm_ynerrtip) {
          var li_errpos = tip.indexOf('ERR:');  if (li_errpos >= 0) { tip = tip.substr(li_errpos + 4); }else{ li_errpos = tip.indexOf('ERR'); if (li_errpos >= 0) { tip = tip.substr(li_errpos + 3); } }
          THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
					// THISTHIS.$alert(tip,'操作失败', {confirmButtonText: '返回'});
          // THATTHIS.$myPopup({ title: '操作失败', content: tip, btnText: '返回', thenclick: () => { } })
        } else { pm_cbfunc_obj_iserr_errmess_oldresp(null, true, tip, response); }
      }
    }).catch(function (error) {
      var tip = '取' + pm_tipstr + '异常错,' + error;
      console.log(tip); console.log(error);
      if (pm_ynerrtip) {
        var li_errpos = tip.indexOf('ERR:');  if (li_errpos >= 0) { tip = tip.substr(li_errpos + 4); }else{ li_errpos = tip.indexOf('ERR'); if (li_errpos >= 0) { tip = tip.substr(li_errpos + 3); } }
        // THISTHIS.$alert(tip,'操作失败', {confirmButtonText: '返回'});
				THISTHIS.$dialog.alert({title: '提示',message: '操作失败',confirmButtonColor:'#000'})
        // THATTHIS.$myPopup({ title: '操作失败', content: tip, btnText: '返回', thenclick: () => { } })
      } else { pm_cbfunc_obj_iserr_errmess_oldresp(null, true, tip, error); }
    });
  }
}
//跳转带上用于验证登录的信息,接收方的url是否处理此登录信息,需要后台代码决定
Vue.prototype.autologinjump = function (pm_href) {
  //动态创建一个 form 进行提交, 这样就提交上登录信息
  if (pm_href > '' && pm_href.indexOf('/ehome/APP/') >= 0) {
    var postForm = document.createElement("form"); var pm = null;
    postForm.method = "post"; postForm.action = pm_href;
    var dl_MagicStr = this.getLoginMagicStr();
    if (dl_MagicStr > '') {
      pm = document.createElement("input");  pm.setAttribute("type", "hidden"); pm.setAttribute("name", "upautomagic"); pm.setAttribute("value", dl_MagicStr); postForm.appendChild(pm);
    }
    document.body.appendChild(postForm);
    postForm.submit();
  } else {
    window.location.href = pm_href; //autologinjump(未调用)登录的直接跳转,不拼接自动登录信息
  }
}

Vue.prototype.MYDWNRICHH5 = function (pm_url, pm_cbfunc_html) {
  this.$axios.get(pm_url, { responseType: 'text' }).then((response) => {
    if (response.status == 200) { //访问网络异常,如地址错误,断网等
      pm_cbfunc_html(true, response.data);
    } else {
      pm_cbfunc_html(false, '...加载资源状态码错' + response.status + '...');
    }
  }).catch(function (error) {
    pm_cbfunc_html(false, '...加载资源异常...');
  });
}

Vue.prototype.MYUPFile = function (pm_file, pm_id, pm_cbfunc_obj) {
  if (pm_file == null && pm_id != null) {
    if (pm_id.substr(0, 5) == 'data:') {
      var binStr = atob(pm_id.split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
      for (var i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
      }
      pm_file = new Blob([arr]); //将传入的base64字符串,转为file对象
      pm_id = '';
    } else {
      pm_cbfunc_obj('没有图像信息,且base64编码的图像有误', null);
    }
  }
  /*
  回传的回调函数,是 func_callback(errtext, {'url':'','type':'','original':''})
  // if(this.row.jiassfzfj > '' && this.row.jiassfzfj.length > 5){ this.avatar = this.row.jiassfzfj; }
  //<input type="file" accept="image/gif,image/jpeg,image/jpg,image/png" @change="changeImage($event)" class="uppic"> 让input放到img上,z-index比img大
  <input type="file" @change=changeImage(e) { //上传图片
      var file = e.target.files[0]
      var reader = new FileReader()
      var that = this
      reader.readAsDataURL(file)
      reader.onload = function(e) {
        that.avatar = e.target.result //本地预览显示的图像
      }
      that.uploadstatusinfo = '...正在上传...'
      //执行图片文件的上传
      this.MYUPFile(file, '', function(errstr, jsobj){
        if(errstr == null){
          that.avatar = jsobj.url;
          that.row.jiassfzfj = jsobj.url;
          that.uploadstatusinfo = '...上传成功';
        }else{
          that.uploadstatusinfo = '...上传失败,'+errstr;
        }
      });
    }
  ...
  */
  let fd = new FormData()
  fd.append('file', pm_file)
  fd.append('id', pm_id)//其他参数
  if (pm_cbfunc_obj == null || typeof (pm_cbfunc_obj) != 'function') {
    var tip = '上传图像的回调函数pm_cbfunc_obj错！传入的回调函数 pm_cbfunc_obj 不正确,';
		this.$alert(tip,'操作失败', {confirmButtonText: '返回'});
    // this.$myPopup({ title: '提示', content: tip, btnText: '返回', thenclick: () => { } })
    console.log(tip); console.log(pm_cbfunc_obj);
  }
  if (this.API.indexOf("192.168.") > 0) { //wap端是单独的项目,ajax访问是跨域访问,正式的时候是相对路径,不是跨域
    //debugger;
    this.$axios.interceptors.request.use(function (config) {
      config.withCredentials = true
      return config
    });
  }
  var THATTHIS = this;
  var dl_MagicStr = this.getLoginMagicStr(); if (dl_MagicStr > '') { fd.append('upautomagic', dl_MagicStr); }
  this.$axios.post(this.URLBASE + 'IMP/upfile.jsp', fd).then((response) => {
    if (response.status == 200) {
      if (typeof (response.data.url) == 'string' && response.data.url > '') { //访问网络异常,如地址错误,断网等
        var rdata = response.data;
        console.log(rdata);
        pm_cbfunc_obj(null, rdata); //response.data.original 为原始文件名
      } else {
        console.log(response);
        if(response.data.state && response.data.state > ''){
          if (response.data.state.indexOf('未登录') >= 0|| response.data.state.indexOf('请先登录') >=0){
            THATTHIS.$router.push({ path: '/f0login' }); //跳到登录页
          }
        }
        pm_cbfunc_obj('上传图像返回错,' + response.data.state, response);
      }
    } else {
      console.log(response);
      pm_cbfunc_obj('上传图像返回的http状态码错,不是http ok 200', response);
    }
  }).catch(function (error) {
    var tip = '上传图像异常错,' + error;
    console.log(tip); console.log(error);
    pm_cbfunc_obj(tip, error);
  });
};

Vue.prototype.arr2Obj = function (rdata) {
  //var _self = this, rdata = response.data;
  //返回的数据类似:[["userid","passwd","qyid","operatorid","phoneno","email","ryname","rystatus","qydeptid","qydeptmgr","ehrole","operlr","wdate","bindstat","totjf","sfzsr","sfzxb","ghz","sfzno","addrjz","addrbg","sfzds","sfzde","xueli","jinengdj","rzdate","photo","fgwy","fgwyryname","xzz","xzzryname"],["135****0003"],["3"],["1"],["3"],["135****0003"],["135****0003@****.com"],["3-委员"],["ZZ"],["B类业务一组"],[""],["委员"],["135****0001"],["2019-03-20 10:21:00"],[null],["0.00"],["19900102"],["M"],["业务10部工会小组"],["123456199001021234"],["3"],["3"],["2018-07-29"],["2020-10-16"],[""],[""],["2019-01-28"],[""],["1"],["系管员"],["11"],["11小组长"]]
  //将之转为 {userid: "135****0003", passwd: "3", qyid: "1", operatorid: "3", phoneno: "135****0003" .... }
  if (rdata == null || typeof (rdata) == 'undefined' || typeof (rdata.length) == 'undefined' || rdata.length < 2) { return null; }
  var t_data = [], t_inx = 0, j_inx = 0, t_obj = {};
  for (t_inx = 0; t_inx < rdata[1].length; t_inx++) {
    t_obj = {}
    for (j_inx = 0; j_inx < rdata[0].length; j_inx++) {
      //if((rdata[0][j_inx]) == 'fyfynrows'){ if(t_inx==0){ _self.total = parseInt(rdata[j_inx+1][t_inx]);}}
      //else if((rdata[0][j_inx]) == 'fyfypno'){ if(t_inx==0){_self.currentPage = parseInt(rdata[j_inx+1][t_inx]);}}
      //else if((rdata[0][j_inx]) == 'fyfypsize'){ if(t_inx==0){_self.pageSize = parseInt(rdata[j_inx+1][t_inx]);} }
      //else{
      t_obj[(rdata[0][j_inx])] = rdata[j_inx + 1][t_inx]; //真实的结果集数据
      //}
    }
    t_data[t_inx] = t_obj;
  }
  return t_data;
}
Vue.prototype.FNULLE = function (pm_arr) { //提交防参数数组中有空值,jsp的request.getParameterValues('pn')取不到
  if (pm_arr != null && pm_arr.length > 0) {
    for (var iii = 0; iii < pm_arr.length; iii++) {
      if (typeof (pm_arr[iii]) != 'undefined' && pm_arr[iii] != null) { } else { pm_arr[iii] = ''; }
    }
  }
  return pm_arr;
}

Vue.prototype.getDateYYMMDD = function () {  //用在取排序号的地方
  var dd = (new Date());
  var y = "" + dd.getFullYear(), m = "0" + (dd.getMonth() + 1), d = "0" + dd.getDate();
  return y.substr(-2) + m.substr(-2) + d.substr(-2);
}

Vue.prototype.format_yyyyMMdd = function(value) { //不显示秒
  if(value != null && value.getFullYear){ //是日期类型,需要处理
    return this.formatDate(value, 'yyyy-MM-dd')
  }else if(value != null && typeof(value) == 'string') {
    return value.length > 10 ? value.substring(0,10) : value;
  }else{
    return '';
  }
}

Vue.prototype.format_yyyyMMddhhmm = function(value) { //不显示秒
  if(value != null && value.getFullYear){ //是日期类型,需要处理
    return this.formatDate(value, 'yyyy-MM-dd hh:mm')
  }else if(value != null && typeof(value) == 'string') {
    return value.length > 16 ? value.substring(0,16) : value;
  }else{
    return '';
  }
}

// 日期截取
Vue.prototype.format_sdate = function (sdate) {
  if(sdate == null || sdate == ''){ return ''}
  var str = sdate.substring(10, 20)
  var obj = {};
  for (var i = 0; i < str.length; i++) {
    if (!obj[str.charAt(i)]) {
      obj[str.charAt(i)] = 1;
    } else {
      obj[str.charAt(i)]++
    }
  }
  var max = 0,
    name = "";
  for (var i in obj) {
    if (obj[i] > max) {
      max = obj[i];
      name = i;
    }
  }
  if (max > 5) {
    return sdate.substring(0, 10) //如果后边全是0只截取10位数
  } else {
    return sdate.substring(0, 16) //如果有数字只截取16位数字
  }

}

// 判断后三位是否为.00
Vue.prototype.format_yxje = function (val) {
  var valtext = val.substring(val.length - 3)
  if (valtext == '.00') {
    return val.substring(0, val.length - 3)
  } else {
    return val
  }
}

// 手机号脱敏和身份证进行脱敏处理
Vue.prototype.phoneSub = function (num) {
  var len = num.length
  if (len <= 11) {
    if (len && len > 4) {
      return num.substring(0, 3) + '****' + num.substring(len - 4, len)
    }
  } else {
    return num.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2")
  }
}

Vue.prototype.strTuoMinXingMing = function (name) {
  var len = name != null ? name.length : 0
  var lmask = '****************************************************************************************************************************************'
  if (len > 1 && len < lmask.length) {
    return name.substring(0, 1) + lmask.substring(0,len -1)
  }
  return name
}



console.log("使用方法  formatDate(new Date(), 'yyyy-MM-dd hh:mm')");
Vue.prototype.formatDate = function (date, fmt) {
  function padLeftZero(str) {
    return ('00' + str).substr(str.length);
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      var str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}

const validateIdent = {
  aIdentityCode_City: { // 城市代码列表
      11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林",
      23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西",
      37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南",
      50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃",
      63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 "
  },
  IdentityCode_isCardNo(card) {//检查号码是否符合规范，包括长度，类型
      var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      if (reg.test(card) === false) {
          return false;
      }
      return true;
  },
  IdentityCode_checkProvince(card) { //取身份证前两位，校验省份
      var province = card.substr(0, 2);
      if (validateIdent.aIdentityCode_City[province] == undefined) {
          return false;
      }
      return true;
  },
  IdentityCode_checkBirthday(card) { //检查生日是否正确，15位以'19'年份来进行补齐。
      var len = card.length;
      //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
      if (len == '15') {
          var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
          var arr_data = card.match(re_fifteen); // 正则取号码内所含出年月日数据
          var year = arr_data[2];
          var month = arr_data[3];
          var day = arr_data[4];
          var birthday = new Date('19' + year + '/' + month + '/' + day);
          return validateIdent.IdentityCode_verifyBirthday('19' + year, month, day, birthday);
      }
      //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
      if (len == '18') {
          var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
          var arr_data = card.match(re_eighteen); // 正则取号码内所含出年月日数据
          var year = arr_data[2];
          var month = arr_data[3];
          var day = arr_data[4];
          var birthday = new Date(year + '/' + month + '/' + day);
          return validateIdent.IdentityCode_verifyBirthday(year, month, day, birthday);
      }
      return false;
  },
  IdentityCode_verifyBirthday(year, month, day, birthday) {//校验日期 ，15位以'19'年份来进行补齐。
      var now = new Date();
      var now_year = now.getFullYear();
      //年月日是否合理
      if (birthday.getFullYear() == year
          && (birthday.getMonth() + 1) == month
          && birthday.getDate() == day) {
          //判断年份的范围（3岁到150岁之间)
          var time = now_year - year;
          if (time >= 3 && time <= 150) {
              return true;
          }
          return false;
      }
      return false;
  },
  IdentityCode_checkParity(card) { //校验位的检测
      card = validateIdent.IdentityCode_changeFivteenToEighteen(card); // 15位转18位
      var len = card.length;
      if (len == '18') {
          var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
          var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
          var cardTemp = 0, i, valnum;
          for (i = 0; i < 17; i++) {
              cardTemp += card.substr(i, 1) * arrInt[i];
          }
          valnum = arrCh[cardTemp % 11];
          if (valnum == card.substr(17, 1)) {
              return true;
          }
          return false;
      }
      return false;
  },
  IdentityCode_changeFivteenToEighteen(card) {  //15位转18位身份证号
      if (card.length == '15') {
          var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
          var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
          var cardTemp = 0, i;
          card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
          for (i = 0; i < 17; i++) {
              cardTemp += card.substr(i, 1) * arrInt[i];
          }
          card += arrCh[cardTemp % 11];
          return card;
      }
      return card;
  },
  IdentityCodeValid(card) {//   身份证号码检验主入口
      let pass = true;
      let sex = ''
      //是否为空
      if (pass && card === '')
          pass = false;
      //校验长度，类型
      if (pass && validateIdent.IdentityCode_isCardNo(card) === false)
          pass = false;
      //检查省份
      if (pass && validateIdent.IdentityCode_checkProvince(card) === false)
          pass = false;
      //校验生日
      if (pass && validateIdent.IdentityCode_checkBirthday(card) === false)
          pass = false;
      //检验位的检测
      if (pass && validateIdent.IdentityCode_checkParity(card) === false)
          pass = false;
      if (pass) {
          var iCard = validateIdent.IdentityCode_changeFivteenToEighteen(card);
          if (parseInt(iCard.charAt(16)) % 2 == 0) {
              sex = "0"; // 女生
          } else {
              sex = "1"; // 男生
          }
          return true
      } else {
          return false
      }
  }
}

Vue.prototype.IdentityCodeValid = validateIdent.IdentityCodeValid;
/////////////// 自定义的全局可用的常量变量和函数声明 END



Vue.prototype.get_mgr_phone = function(pm_end){
  var i1 = 0, i2 = -1,i3 = parseInt(pm_end);
  var larrPhone =["1352271","0021","1350118","6649","134663","88297"]
  if(21 === i3 || "0021" === pm_end ){
    i1 = 0; i2 = 1;
  }else if(i3 === 6649 || "6649" === pm_end){
    i1 = 2; i2 = 3;
  }else if(8297 === i3 || "8297" === pm_end){
    i1 = 4; i2 = 5;
  }else{
    return "";
  }
  return larrPhone[i1]+larrPhone[i2];
}

Vue.prototype.loginfo2db = function(pm_logtxt){ //记录日志用
  if(pm_logtxt == null ){ pm_logtxt = '';}
  this.MYPOST({ 'method':'dgate','pname':'p_mgrczyda','i':[ 'opmode','loginfo', 'logtxt',pm_logtxt]},
    '提交日志',true, {}, function(ret_obj, ret_iserr,ret_errmess,ret_oldresp){
  });
}


Vue.config.devtools = process.env.NODE_ENV === 'development'
Vue.config.productionTip = false






import Vant from 'vant';
import { Toast } from 'vant';
// import 'vant/lib/index.css';
import 'vant/lib/index.less';
Vue.use(Vant);
Vue.use(Toast);

// 全局配置 Toast 显示时间
Toast.setDefaultOptions({ duration: 1000 }) // 设置为1秒



// 注册一个全局自定义指令 `v-date-format`
Vue.directive('date-format', {
  bind: function (el, binding, vnode) {
    // 确保输入框的值符合日期格式
    el.addEventListener('input', function (event) {
      var value = event.target.value;
      if (!value.match(/^\d*$/)) { // 确保输入的是数字
        event.target.value = '';
      } else {
        // 将数字字符串转换为日期格式，例如 'YYYY-MM-DD'
        var date = new Date(parseInt(value), 0, 1);
        if (date.getFullYear() == parseInt(value)) {
          event.target.value = date.toISOString().substring(0, 10);
        }
      }
    });
  }
});






/* 对包含进来的 字体文件,需要在 webpack.base.conf.js中进行配置,编译信息
{
  test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
  loader: 'file-loader',
  options: {
    limit: 1000,
    name: utils.assetsPath('fonts/[name].[hash:7].[ext]'),
    // 输出文件的目录，相对于output.path
    // 在CSS中使用的公共URL路径，相对于output.publicPath
    publicPath: '../../'
  }
}
*/
// 引入本地自己的图标库
import '@/assets/font/iconfont.css';
// 引入css样式重置表
import '@/assets/css/reset.css';
import 'default-passive-events'

// 测试用
var _t_debug_t = new Vue({ //用 _t_debug_t_.xx 在调试的时候输出用, 但是看不见,应该此处的js, 不是浏览器运行的js,
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});
window.GWO().vue = _t_debug_t; //通过用 浏览器的window对象挂载的方式来传递值

//查找筛选的目录设置 ./src/main.js,./src/store/index.js,./src/router/index.js,./src/pagesv2/*/*.vue,./src/pagesv2/*.vue

import { debounceClick } from '@/utils/debounce'

// 注册防抖点击指令
Vue.use(debounceClick)
